<template>
  <!-- 农资投入查询 -->
  <BaseMainSlot>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="27"
        :has-add="false"
        :has-del="false"
        :has-edit="false"
        :has-cancel="false"
        :has-edit-column="true"
        @showColumn="showColumn"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" :showSelectColumn="false">
        <template v-slot:facilityBOList="{ row }">
          <template v-if="!row.index">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="seeEquip(row)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </template>
        <template v-slot:handlerName="{ row }">
          <template v-if="!row.index">
            <span v-if="row.personName">{{ row.personName }}</span>
            <span v-else>—</span>
          </template>
        </template>
        <template v-slot:assetQuantity="{ row }">
          <template v-if="!row.index">
            <div>{{ row.assetQuantity }}{{ row.unitName }}</div>
          </template>
        </template>
        <template v-slot:spec="{ row }">
          <template v-if="!row.index">
            <div>
              {{ row.materialDTO.specification }}
              {{ row.materialDTO.perSpecUnitName }}
              {{ row.materialDTO.perSpecUnitName ? '/' : '' }}
              {{ row.materialDTO.unitName }}
            </div>
          </template>
        </template>
        <template v-slot:pictureNo="{ row }">
          <template v-if="!row.index">
            <el-button
              v-if="row.pictureNo"
              type="success"
              plain
              size="small"
              @click="upimage(row.pictureNo)"
            >查看图片</el-button>
            <el-button v-else type="text" disabled>暂无图片</el-button>
          </template>
        </template>
        <template v-slot:batchName="{ row, item }">
          <template v-if="!row.index">
            {{ row.productionBatchBO ? row.productionBatchBO[item.prop] : '' }}
          </template>
        </template>
        <template v-slot:materialName="{ row, item }">
          <template v-if="!row.index">
            {{ row.materialDTO ? row.materialDTO[item.prop] : '' }}
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        class="dialog"
        title="查看农资图片"
        :visible.sync="dialogFormVisible"
      >
        <img :src="imgUrl" />
      </el-dialog>

      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :tableColumn="allTableColumn"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogTableColumnVisible = false">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="saveColumn"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>

      <SeeEquip
        :is-show-equip="isShowEquip"
        :equip-data="facilityBOList"
        @closeDialog="isShowEquip = false"
      />
    </template>
  </BaseMainSlot>
</template>
<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import SeeEquip from '@/components/seeEquip'
import Pagination from "@/components/Pagination";
import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
// import moment from "moment";
import danwei from "@/api/basic-info-manage/unit-manage/index";
import nowpagereq from "@/api/basic-info-manage/agr-source-base-Manage/index";
import nowstaff from "@/api/digital-operation/personnel-cost-mansge/staff-manage/index";
import userreq from "@/api/user/index"
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import collectionPicture from "@/api/digital-production/collectionPicture/index";
import { mymixin } from "@/utils/mixin";
// import { getToken } from '@/utils/auth';
export default {
  name: "AgrInputQuery",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot, SeeEquip },
  mixins: [mymixin],
  data () {
    return {
      tableColumn: [
        { prop: 'batchName', label: '批次名称', minWidth: '200', slotName: 'batchName' },
        { prop: 'batchNo', label: '批次号', minWidth: '120', slotName: 'batchName' },
        { prop: 'facilityBOList', label: '设施名称', minWidth: '120', slotName: 'facilityBOList' },
        { prop: 'materialName', label: '投入农资名称', minWidth: '120', slotName: 'materialName' },
        { prop: 'handlerName', label: '经手人', width: '120', slotName: 'handlerName' },
        { prop: 'assetQuantity', label: '投入量', minWidth: '120', slotName: 'assetQuantity' },
        { prop: 'spec', label: '规格', minWidth: '120', slotName: 'spec' },
        { prop: 'pictureNo', label: '农资图片', minWidth: '120', slotName: 'pictureNo' },
        { prop: 'assetDate', label: '投入日期', minWidth: '120' },
      ],
      formConfig: [
        {
          label: '批次名称',
          prop: 'batchNo',
          type: 'select',
          options: [], // batchList
          optionKey: { label: 'batchName', value: 'batchNo' },
        }, {
          label: '设施名称',
          prop: 'facilityNo',
          type: 'select',
          options: [], // facilityList
          optionKey: { label: 'facilityName', value: 'facilityNo' }
        }, {
          label: '农资名称',
          prop: 'materialNo',
          type: 'select',
          options: [], // queryagriculturalMaterialList
          optionKey: { label: 'materialName', value: 'materialNo' },
        }, {
          label: '经手人',
          prop: 'personNo',
          type: 'select',
          options: [], // StaffList
          optionKey: { label: 'personName', value: 'personNo' }
        }, {
          label: '选择时间',
          prop: 'date',
          type: 'daterange',
        },
      ],
      agriculturalMaterialNameLike: "", // 品种名称模糊查询
      // 单位选择列表
      unitlist: [],
      // 农资选择列表
      agrSourseTypeList: [],
      // 已选择的农资列表
      selectnozilist: [],
      agriculturalMaterialTypeName: "",
      // 校验规则
      //   rules: {},
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      nowselectedList: [],
      dialogFormVisible: false,
      // 农资图片
      imgUrl: "",
      // 搜索提交
      searchlist: {},
      batchNo: "",
      facilityNo: "",
      materialNo: "",
      // 批次
      batchList: [],
      // 设施
      facilityList: [],
      facilityAList: [],
      // 农资名称
      agriculturalMaterialList: [],
      queryagriculturalMaterialList: [],
      // 员工
      staffList: [],
      StaffList: [],
      personNo: "",
      facilityBOList: [],
      isShowEquip: false
    };
  },
  watch: {
    nowChanceStau (newval) {
      // 当状态为删除的时候触发删除方法---另外的删除修改添加，通过点击保存，调用方法来实现
      if (newval === "add") {
        this.selectnozilist = [];
        this.agriculturalMaterialTypeName = "";
      }
    }
  },
  mounted () {
    this.getselectmessage();
    this.getTableDataList();
    this.tableData = [];
  },
  methods: {
    seeEquip (row) {
      console.log('a');
      this.facilityBOList = row.facilityBOList
      this.isShowEquip = true
      console.log(this.isShowEquip);
      console.log(row.facilityBOList);
    },
    // 获取当前表格信息
    getTableDataList () {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          batchNo: this.searchlist.batchNo || undefined,
          facilityNo: this.searchlist.facilityNo || undefined,
          startTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          endTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
          materialNo: this.searchlist.materialNo || undefined,
          personNo: this.searchlist.personNo || undefined,
          farmingTypeNo: sessionStorage.farmingTypeNo,
          organizationNo: sessionStorage.organizationNo
        }
      };
      this.entity = params.entity
      managementtwo.getTableDataList(params).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("当前农业类型表格获取失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        // console.log(this.tableData)
        this.addblankmet();
        this.resetActionBar();
      });
    },
    // 获取下拉数据
    getselectmessage () {
      // 获取单位选择框数据
      danwei.getallunitlist().then((res) => {
        this.unitlist = res.data;
      });
      nowstaff.getStaffListByCondition().then(res => {
        this.StaffList = res.data;
        this.formConfig[3].options = res.data.map(el => {
          return { ...el, personName: el.person?.name }
        });
      });
      // 获取批次选择框数据
      managementtwo.queryBatchListName().then((res) => {
        this.batchList = res.data;
        this.formConfig[0].options = res.data;
      });
      let params = {};
      if (this.nowChanceStau === "add") {
        params = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(","),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
          facilityStatus: 1
        };
      } else {
        params = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(",").concat([sessionStorage.parentId || '']),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo")
        };
      }
      // 获取设施选择框数据 queryFacilityListName
      userreq.getfacilityAll(params).then((res) => {
        this.facilityList = res.data;
        this.formConfig[1].options = res.data;
      });
      managementtwo.queryFacilityName().then((res) => {
        this.facilityAList = res.data;
      });
      managementtwo.getqueryList("").then((res) => {
        this.queryagriculturalMaterialList = res.data;
        this.formConfig[2].options = res.data;
      });
      // 获取农资下拉内容
      nowpagereq.getqueryList("").then(
        res => {
          let data = res.data
          // 赋值总条数
          // this.totalSize = data.totalElements;
          // 赋值数组
          this.agriculturalMaterialList = data
        })
    },
    // 农资数据处理掉空child
    // 循环过滤树形数组
    filterArrForKey (arr) {
      let newArr = [];
      newArr = arr.map((item) => {
        if (item.child.length > 0) {
          item = {
            ...item,
            child: this.filterArrForKey(item.child)
          };
        } else {
          delete item.child;
        }
        return item;
      });
      newArr = newArr.filter((item) => item != null);
      return newArr;
    },
    cascaderChange (e) {
      // console.log(e);
    },
    // 查询当前图片
    upimage (e) {
      this.imgUrl = ""
      this.dialogFormVisible = true
      // managementtwo.getimage(e).then(res => {
      //   let data = res.data
      //   this.imgUrl = `data:image/png;base64,${data.pictureData}`
      //   // console.log(this.imgUrl)
      // })
      if (e) {
        // return this.basicUrl + query/ + this.pictureIdthis.pictureNo = this.formData.pictureNo;
        collectionPicture.getColectPicture2(e).then(res => {
          this.imgUrl = "data:image/png;base64," + res.data.pictureData;
        });
      } else {
        this.imgUrl = "";
      }
    },
    dateFormat (row, colnum) {
      if (row.inputsRecordNo) {
        // console.log(row)
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD MM:SS:mm");
      }
    },
    search () {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize (pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage (currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 表格点击
    handleEdit (list) {
      this.formData = list;
      let testname = list.agriculturalMaterialType;
      this.selectnozilist = [];
      if (testname) {
        this.agriculturalMaterialTypeName =
          testname.agriculturalMaterialTypeName;
      } else {
        this.agriculturalMaterialTypeName = "";
      }

      this.editActive = true;
    },
    handleSelectionChange (list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map((item) => {
        return item.materialNo;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    delmessage () {
      if (this.nowChanceStau === "del") {
        managementtwo.delmeslist(this.nowselectedList).then((res) => {
          if (res.code === 1) {
            this.getTableDataList();
            this.$message.success("删除成功");
          } else {
            this.$message.error("删除失败");
          }
        });
      }
    },
    save () {
      if (this.nowChanceStau === "add") {
        let parone = {
          ...this.formData,
          agriculturalMaterialTypeId:
            this.selectnozilist[this.selectnozilist.length - 1]
        };
        managementtwo.addmeslist(parone).then((res) => {
          if (res.code === 1) {
            this.getTableDataList();
            this.$message.success("添加成功");
          } else {
            this.$message.error("添加失败");
          }
        });
      }
      if (this.nowChanceStau === "edit") {
        let params = this.formData;
        delete params["agriculturalMaterialType"];
        if (this.selectnozilist === []) {
          //   console.log("")
        } else {
          delete params["agriculturalMaterialTypeName"];
          params["agriculturalMaterialTypeId"] =
            this.selectnozilist[this.selectnozilist.length - 1];
        }
        managementtwo.editmeslist(params).then((res) => {
          if (res.code === 1) {
            this.getTableDataList();
            this.$message.success("修改成功");
          } else {
            this.$message.error("修改失败");
          }
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.tabhid {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  // background-color: #0cb28c;
}
.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
}
::v-deep .staff-manage .common-layout .content {
  overflow-y: auto;
}
.upimg {
  ::v-deep .xunzeimage {
    width: 140px !important;
  }
}
.dialog {
  height: 90%;
  text-align: center;
  // img{
  //   width: 100%;
  // }
}
</style>
